import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_1800/pages/goods/GoodsDetail.dart';
import 'package:flutter_1800/pages/widgets/MyText.dart';
import 'package:flutter_1800/service/api_service.dart';
import 'package:flutter_1800/tools/AppUtil.dart';
import 'package:flutter_1800/tools/config.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class Search extends StatefulWidget {
  const Search({Key? key}) : super(key: key);

  @override
  _SearchState createState() => _SearchState();
}

class _SearchState extends State<Search>
    with AutomaticKeepAliveClientMixin, RouteAware {
  var cates = [];
  var selectCate = null;

  var children = [];

  final RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  @override
  void initState() {
    super.initState();
  }

  @override
  bool get wantKeepAlive => true;

  //回到当前页面
  @override
  void didPopNext() {
    print("返回了");
  }

  @override
  void didPop() {
    print("返回了");
  }

  void _onRefresh() async {
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    _refreshController.loadComplete();
  }

  ///see AutomaticKeepAliveClientMixin

  void queryGoods(id) {
    ApiService.queryGoods(id).then((value) {
      setState(() {
        children = value["data"];
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);

    return Scaffold(
        appBar: AppBar(
          shadowColor: Colors.transparent,
          centerTitle: true,
          elevation: 0.0,
          toolbarHeight: 40,
          title: MyText(
            "商品搜索",
            weight: FontWeight.bold,
          ),
        ),
        backgroundColor: Colors.white,
        body: Column(
          children: [
            Container(
              margin: EdgeInsets.fromLTRB(
                  AppUtil.getPadding(), 0, AppUtil.getPadding(), 0),
              padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
              decoration: BoxDecoration(
                  color: const Color(0xffeeeeee),
                  borderRadius: BorderRadius.circular(10)),
              child: const Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Icon(
                    Icons.search,
                    color: Color(0xffaaaaaa),
                  ),
                  SizedBox(width: 6),
                  Expanded(
                      child: TextField(
                    style: TextStyle(),
                    maxLines: 1,
                    textAlignVertical: TextAlignVertical.center,
                    decoration: InputDecoration(
                        border: InputBorder.none,
                        hintText: "请输入搜索的商品",
                        hintStyle: TextStyle(color: Color(0xffaaaaaa))),
                    //       如何监听TextField的输入变化
                    // 1. 监听onChanged
                    // 2. 监听controller
                  ))
                ],
              ),
            ),
            Expanded(
                child: Container(
                    padding: AppUtil.getCommonPadding(),
                    child: SmartRefresher(
                        enablePullDown: true,
                        enablePullUp: true,
                        controller: _refreshController,
                        onRefresh: _onRefresh,
                        onLoading: _onLoading,
                        cacheExtent: 1000,
                        physics: const BouncingScrollPhysics(),
                        child: GridView.builder(
                          shrinkWrap: true,
                          padding: const EdgeInsets.only(
                            top: 10,
                          ),
                          gridDelegate:
                              const SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: 3,
                            mainAxisSpacing: 10,
                            crossAxisSpacing: 10,
                            childAspectRatio: 1 / 1.4,
                          ),
                          itemBuilder: (context, index) {
                            Map item = children[index];
                            return GestureDetector(
                              onTap: () {
                                AppUtil.getTo(GoodsDetail(item["id"]));
                              },
                              child: Column(
                                children: [
                                  AspectRatio(
                                    aspectRatio: 1 / 1,
                                    child: ClipRRect(
                                      borderRadius: BorderRadius.circular(4),
                                      child: CachedNetworkImage(
                                        imageUrl: item["extra"],
                                        fit: BoxFit.cover,
                                      ),
                                    ),
                                  ),
                                  const SizedBox(height: 5),
                                  MyText(
                                    item["name"]["cn"],
                                    color: AppConfig.font1,
                                  )
                                ],
                              ),
                            );
                          },
                          itemCount: children.length,
                        ))))
          ],
        ));
  }
}
